<template>
  <div class="menu-manager">
    <el-card class="box-card">
      
      <el-row :gutter="20">
        <!-- 角色列表 -->
        <el-col :span="8">
          <el-card>
            <el-table
              :data="roles"
              highlight-current-row
              @current-change="handleRoleSelect"
              style="width: 100%">
              <el-table-column
                prop="roleName"
                label="角色名称">
              </el-table-column>
              <el-table-column
                prop="roleCode"
                label="角色编码">
              </el-table-column>
            </el-table>
          </el-card>
        </el-col>
        
        <!-- 菜单树 -->
        <el-col :span="16">
          <el-card v-if="selectedRole">
            <div slot="header">
              <span>{{ selectedRole.roleName }} - 菜单权限</span>
              <el-button
                style="float: right; padding: 3px 0"
                type="text"
                @click="saveMenuAssignment">
                保存修改
              </el-button>
            </div>
            <el-tree
              ref="menuTree"
              :data="menuTree"
              show-checkbox
              node-key="id"
              :props="defaultProps"
              :check-strictly="false"
              :default-expand-all="true"
              @check-change="handleCheckChange">
            </el-tree>
          </el-card>
          <el-card v-else>
            <div class="empty-tip">
              请选择左侧的角色
            </div>
          </el-card>
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>

<script>
import request from '@/utils/request'

export default {
  name: 'MenuManager',
  data() {
    return {
      roles: [],
      selectedRole: null,
      menuTree: [], // 完整的系统菜单树
      roleMenuIds: [], // 当前选中角色拥有的菜单ID列表
      defaultProps: {
        children: 'children',
        label: 'menuName'
      }
    }
  },
  created() {
    this.loadRoles()
    this.loadSystemMenuTree() // 加载系统完整菜单树
  },
  methods: {
    // 加载角色列表
    async loadRoles() {
      try {
        const response = await request.get('/roles')
        this.roles = response
      } catch (error) {
        console.error('获取角色列表失败:', error)
        this.$message.error('获取角色列表失败')
      }
    },
    
    // 加载系统完整菜单树
    async loadSystemMenuTree() {
      try {
        const response = await request.get('/menu/sysMenuTree')
        this.menuTree = response
      } catch (error) {
        console.error('获取系统菜单树失败:', error)
        this.$message.error('获取系统菜单树失败')
      }
    },
    
    // 递归提取菜单ID，只提取叶子节点的ID
    extractMenuIds(menus) {
      const ids = []
      const traverse = (items) => {
        if (!Array.isArray(items)) return
        items.forEach(item => {
          if (item && typeof item === 'object' && 'id' in item) {
            // 只有当没有子节点或子节点为空时才添加ID
            if (!item.children || !Array.isArray(item.children) || item.children.length === 0) {
              ids.push(item.id)
            }
            // 如果有子节点，继续遍历
            if (item.children && Array.isArray(item.children)) {
              traverse(item.children)
            }
          }
        })
      }
      traverse(menus.data || menus)
      return ids
    },
    
    // 选择角色时加载该角色的菜单权限
    async handleRoleSelect(role) {
      this.selectedRole = role
      if (role) {
        try {
          // 获取角色的菜单权限
          const response = await request.get(`/menu/role/${role.id}`)
          // 提取角色拥有权限的菜单ID
          this.roleMenuIds = this.extractMenuIds(response)
          
          // 重置树的选中状态
          this.$nextTick(() => {
            if (this.$refs.menuTree) {
              // 先清空所有选中状态
              this.$refs.menuTree.setCheckedKeys([])
              // 再设置实际的选中状态
              this.$refs.menuTree.setCheckedKeys(this.roleMenuIds)
            }
          })
        } catch (error) {
          console.error('获取角色菜单权限失败:', error)
          this.$message.error('获取角色菜单权限失败')
        }
      } else {
        this.roleMenuIds = []
        if (this.$refs.menuTree) {
          this.$refs.menuTree.setCheckedKeys([])
        }
      }
    },
    
    // 处理选中状态变化
    handleCheckChange(data, checked) {
      console.log('菜单选中状态变化:', data.menuName, checked)
    },
    
    // 保存菜单分配
    async saveMenuAssignment() {
      if (!this.selectedRole) {
        this.$message.warning('请先选择角色')
        return
      }
      
      try {
        const checkedKeys = this.$refs.menuTree.getCheckedKeys()
        const halfCheckedKeys = this.$refs.menuTree.getHalfCheckedKeys()
        // 合并完全选中和半选中的节点ID
        const allSelectedKeys = [...checkedKeys, ...halfCheckedKeys]
        
        await request.post('/menu/assign', {
          roleId: this.selectedRole.id,
          menuIds: allSelectedKeys
        })
        
        this.$message.success('保存成功')
        await this.handleRoleSelect(this.selectedRole)
      } catch (error) {
        console.error('保存失败:', error)
        this.$message.error('保存失败')
      }
    }
  }
}
</script>

<style scoped>
.menu-manager {
  padding: 20px;
}
.box-card {
  margin-bottom: 20px;
}
.empty-tip {
  text-align: center;
  color: #909399;
  padding: 20px;
}
</style> 